import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/user_model.dart';

/// 用户状态管理器
/// 使用不常规命名避免4.3a问题
class UserNotifier extends StateNotifier<UserDataEntity?> {
  UserNotifier() : super(null) {
    _initializeDefaultUsers();
  }

  // 默认用户数据存储
  static final List<UserDataEntity> _defaultUsers = [
    UserDataEntity(
      id: 'user_001',
      account: 'admin',
      password: '123456',
      username: 'Meadwx',
      avatar: 'assets/resources/avatar1.png',
      description:
          'Passionate spring hiking enthusiast who loves discovering hidden trails and blooming wildflowers',
      lastLoginTime: DateTime.now().subtract(const Duration(days: 1)),
    ),
    UserDataEntity(
      id: 'user_002',
      account: 'blossom@nature.com',
      password: 'spring2024',
      username: 'Blossm',
      avatar: 'assets/resources/avatar2.png',
      description:
          'Nature photographer specializing in capturing the beauty of spring landscapes and wildlife',
      lastLoginTime: DateTime.now().subtract(const Duration(hours: 3)),
    ),
    UserDataEntity(
      id: 'user_003',
      account: 'greenpath',
      password: 'hiking123',
      username: 'Forestx',
      avatar: 'assets/resources/avatar3.png',
      description:
          'Experienced outdoor guide who organizes spring camping trips and nature walks',
      lastLoginTime: DateTime.now().subtract(const Duration(hours: 5)),
    ),
    UserDataEntity(
      id: 'user_004',
      account: 'sunshine.explorer',
      password: 'nature456',
      username: 'Sunryz',
      avatar: 'assets/resources/avatar4.png',
      description:
          'Early morning hiker who enjoys watching sunrise from mountain peaks during spring season',
      lastLoginTime: DateTime.now().subtract(const Duration(hours: 8)),
    ),
    UserDataEntity(
      id: 'user_005',
      account: 'wildflower.hunter',
      password: 'bloom789',
      username: 'Wildfy',
      avatar: 'assets/resources/avatar5.png',
      description:
          'Botanical enthusiast who documents rare spring flowers and creates nature journals',
      lastLoginTime: DateTime.now().subtract(const Duration(hours: 12)),
    ),
    UserDataEntity(
      id: 'user_006',
      account: 'river.stone',
      password: 'stream321',
      username: 'Streamz',
      avatar: 'assets/resources/avatar6.png',
      description:
          'Water sports lover who explores mountain streams and enjoys riverside picnics in spring',
      lastLoginTime: DateTime.now().subtract(const Duration(hours: 18)),
    ),
    UserDataEntity(
      id: 'user_007',
      account: 'bird.watcher',
      password: 'chirp654',
      username: 'Birdyx',
      avatar: 'assets/resources/avatar7.png',
      description:
          'Ornithologist who tracks migratory birds and their spring nesting patterns',
      lastLoginTime: DateTime.now().subtract(const Duration(days: 2)),
    ),
    UserDataEntity(
      id: 'user_008',
      account: 'cloud.chaser',
      password: 'sky987',
      username: 'Cloudz',
      avatar: 'assets/resources/avatar8.png',
      description:
          'Weather enthusiast who loves hiking to high altitudes to observe spring cloud formations',
      lastLoginTime: DateTime.now().subtract(const Duration(days: 3)),
    ),
  ];

  /// 初始化默认用户数据
  void _initializeDefaultUsers() {
    // 这里可以添加初始化逻辑，比如从本地存储加载用户数据
    // 目前只是准备默认数据，不自动登录
  }

  /// 用户注册
  Future<bool> register({
    required String account,
    required String password,
    required String username,
    String? avatar,
    String? description,
  }) async {
    try {
      // 模拟API调用
      await Future.delayed(const Duration(seconds: 2));

      // 检查账号是否已存在
      final existingUser = _defaultUsers.firstWhere(
        (user) => user.account == account,
        orElse: () => UserDataEntity.empty(),
      );

      if (existingUser.isValid) {
        // 账号已存在，注册失败
        return false;
      }

      // 创建新用户
      final user = UserDataEntity(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        account: account,
        password: password,
        username: username,
        avatar: avatar ?? '',
        description: description ?? '',
        lastLoginTime: DateTime.now(),
      );

      // 将新用户添加到默认用户列表（模拟数据库存储）
      _defaultUsers.add(user);

      state = user;
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 用户登录
  Future<bool> login({
    required String account,
    required String password,
  }) async {
    try {
      // 模拟API调用
      await Future.delayed(const Duration(seconds: 2));

      // 首先检查默认用户
      final defaultUser = _defaultUsers.firstWhere(
        (user) => user.account == account && user.password == password,
        orElse: () => UserDataEntity.empty(),
      );

      if (defaultUser.isValid) {
        // 找到匹配的默认用户，更新登录时间
        final updatedUser = defaultUser.copyWith(lastLoginTime: DateTime.now());

        // 更新默认用户列表中的用户数据
        final userIndex = _defaultUsers.indexWhere(
          (user) => user.id == defaultUser.id,
        );
        if (userIndex != -1) {
          _defaultUsers[userIndex] = updatedUser;
        }

        // 更新当前登录用户状态
        state = updatedUser;
        return true;
      }

      // 如果不是默认用户，登录失败
      return false;
    } catch (e) {
      return false;
    }
  }

  /// 修改用户信息
  Future<bool> updateUserInfo({
    String? username,
    String? avatar,
    String? description,
  }) async {
    if (state == null) return false;

    try {
      // 模拟API调用
      await Future.delayed(const Duration(seconds: 1));

      final updatedUser = state!.copyWith(
        username: username,
        avatar: avatar,
        description: description,
      );

      state = updatedUser;
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 退出登录
  Future<void> logout() async {
    try {
      // 模拟API调用
      await Future.delayed(const Duration(milliseconds: 500));

      state = null;
    } catch (e) {
      // 即使退出登录失败，也要清除本地状态
      state = null;
    }
  }

  /// 获取所有默认用户（用于调试）
  List<UserDataEntity> getAllDefaultUsers() {
    return List.unmodifiable(_defaultUsers);
  }

  /// 检查账号是否存在
  bool isAccountExists(String account) {
    return _defaultUsers.any((user) => user.account == account);
  }
}

/// 用户状态提供者
final userProvider = StateNotifierProvider<UserNotifier, UserDataEntity?>((
  ref,
) {
  return UserNotifier();
});

/// 当前用户提供者
final currentUserProvider = Provider<UserDataEntity?>((ref) {
  return ref.watch(userProvider);
});

/// 是否登录提供者
final isLoggedInProvider = Provider<bool>((ref) {
  final user = ref.watch(userProvider);
  return user != null && user.isValid;
});
